package com.lc.user.controller;

import com.lc.user.bo.RegisterUser;
import com.lc.user.pojo.User;
import com.lc.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/isRegistered/{email}",produces = "application/json")
    public boolean findByEmail(@PathVariable("email") String email){
        return userService.findUserByEmail(email) != null;
    }

    @PostMapping(value = "/register/{email}/{password}/{code}",produces = "application/json")
    public int register(@PathVariable("email") String email, @PathVariable("password") String password,@PathVariable("code") String code){
        RegisterUser user = new RegisterUser();
        user.setEmail(email);
        user.setPassword(password);
        user.setCode(code);
        return userService.register(user);
    }

    @PostMapping(value = "/login/{email}/{password}",produces = "application/json")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response){
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        User res = userService.login(user);
        //将token存放至cookie中
        if(res != null){
            Cookie cookie = new Cookie("token", res.getToken());
            cookie.setPath("/");
            //response.setStatus(200);
            response.addCookie(cookie);
            return res.getEmail();
        }
        return "false";
    }

    @GetMapping(value = "/info/{token}",produces = "application/json")
    public String token(@PathVariable("token") String token, HttpServletResponse response){
        User user = userService.findByToken(token);
        if(user == null){
            //
            response.setStatus(401);
            return null;
        }
        return user.getEmail();
    }

}
